//
//  RDMessageViewController.swift
//  test-ios
//
//  Created by wyz5204 on 2023/5/28.
//

import UIKit
import TangramKit
import DifferenceKit
import RxSwift

class RDMessageViewController: SimpleViewController<RDMessageViewModel> {
    
    private lazy var rootView = {
        return TGLinearLayout(.vert).then { layout in
            layout.backgroundColor = .red
            layout.tg_insetsPaddingFromSafeArea = .all
            layout.tg_insetLandscapeFringePadding = true
        }
    }()
    
    private lazy var headerLayout = {
        // 添加头 主要是 全部和未读
        let headerLayout = TGLinearLayout(.horz)
        headerLayout.tg_height.equal(40)
        headerLayout.tg_width.equal(100%)
        headerLayout.backgroundColor = .green
        return headerLayout
    }()
    
    private lazy var allMessage = {
        return UIButton().then { view in
            view.setTitleAndColor("全部")
        }
    }()
    
    private lazy var unReadMessage = {
        return UIButton().then { view in
            view.setTitleAndColor("未读")
        }
    }()
    
    private lazy var sessionTabelView = {
        let view = UITableView()
        view.dataSource = self
        view.delegate = self
        view.register(cellType: SessionCell.self)
        return view
    }()
    
    override func initView(_ contentView: UIView) {
        super.initView(contentView)
        
        // 设置基本颜色
        if let naviCV = self.navigationController  {
            naviCV.navigationBar.backgroundColor = .white
            naviCV.navigationBar.barTintColor = .white
        }
        
        rootView.addTo(contentView) { view in
            view.snp.makeConstraints { make in
                make.width.equalToSuperview()
                make.bottom.equalToSuperview()
                make.top.equalToSuperview().offset(WPSystem.screen.navigationHeight)
            }
        }
        
        allMessage.tg_top.equal(10)
        allMessage.tg_bottom.equal(10)
        allMessage.tg_left.equal(10)
        allMessage.tg_width.equal(.wrap)
        headerLayout.addSubview(allMessage)
        
        
        unReadMessage.tg_top.equal(10)
        unReadMessage.tg_bottom.equal(10)
        unReadMessage.tg_left.equal(10)
        unReadMessage.tg_width.equal(.wrap)
        headerLayout.addSubview(unReadMessage)
        
        rootView.addSubview(headerLayout)
        
        sessionTabelView.tg_width.equal(100%)
        sessionTabelView.tg_height.equal(100%)
        rootView.addSubview(sessionTabelView)
        
        //debug
        #if DEBUG
        let debug = DebugViewHelper()
        debug.backgroundColor = .red
        debug.setTitleAndColor("测试", color: .white)
        debug.setDebug(DebugViewHelper.Callback(name: "数据库路径", call: {
            Logger.e(RDDBModel.shared().getDBPath())
        }))
        debug.addTo(self.view) { view in
            view.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.right.equalToSuperview()
            }
        }
        #endif
    }
    
    override func bindViewModel(_ viewModel: RDMessageViewModel) {
        
        let output = viewModel.transform(RDMessageViewModel.Input.init())
        
        // 数据表的更新
        output.updateTable.subscribe(onNext: { [weak self]  _ in
            self?.sessionTabelView.reloadData()
        }).disposed(by: rx.disposeBag)
        
        // 进行差量更新
        output.pullData.subscribe (onNext: { [weak self , weak viewModel]  array in
            
            guard let viewModel else {
                return
            }
            guard let self else {
                return
            }
            // 进行UI界面的更新
            let changeset = StagedChangeset(source: viewModel.data, target: array)
            self.sessionTabelView.reload(using: changeset, with: .fade, setData: { value in
                viewModel.data = value
            })
            
        }).disposed(by: rx.disposeBag)
        
        allMessage.rx.tap.subscribe(onNext: { [weak viewModel] _ in
            print("allMessage click ")
            viewModel?.allSession()
        }).disposed(by: rx.disposeBag)
        
        
        unReadMessage.rx.tap.subscribe(onNext: { [weak viewModel] _ in
            Logger.e("adasd" ,"asdasdasd --->" )
            Dispatcher.dispatchWorkClosure {
                Logger.e("adasd" ,"asdasdasd --->" )
            }
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 数据的初始化
        viewModel?.allSession()
    }
    
}
extension RDMessageViewController : UITableViewDataSource , UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.data.count ?? 0
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 62
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(for: indexPath , cellType: SessionCell.self)
        
        if let bean = viewModel?.data[indexPath.row] {
            cell.initBinder(tableView , bean , indexPath)
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard var session = viewModel?.data[indexPath.row] else{
            return
        }
        
//        session.unreadNum = session.unreadNum + 5
//        tableView.reloadRows(at: [indexPath], with: .automatic)
        // 进行界面的跳转
        navigator.show(segue: .openChatSession(session: session), sender: self)
    }
    
}
class RDMessageViewModel : SimpleViewModel,MVVMTransform {
    
    let netModel = RDNetModel.shared
    let localModel = RDDBModel.shared()
    
    var data : [ChatSession] = []
    
    let updateTable = PublishSubject<Void>()
    
    let pullData = PublishSubject<[ChatSession]>()
    
    struct Input {
        
    }
    
    struct Output{
        let updateTable : PublishSubject<Void>
        let pullData : PublishSubject<[ChatSession]>
    }
    
    func transform(_ input: Input) -> Output {
        return Output.init(updateTable: updateTable , pullData: pullData)
    }
    
    func filterUnreadSession(_ bean : ChatSession){
        localModel.saveSingleSession(bean)
    }
    
    /**
     1 先实现网络请求
     */
    func allSession(){
        // 进行本地的数据加载
        let dbList = localModel.getSessionList()
        
        if let dbList {
            // 数据插入
            data.append(contentsOf: dbList)
            
            // 进行界面更新
            updateTable.onNext(())
            
            // 进行界面的更新
            pullSession()
            
            return
        }
        // 本地数据库为空
        pullSession()
    }
    
    func pullSession(){
        // 进行网络请求
        netModel.getSessionList().subscribe(onSuccess: { [weak self] bean in
            guard let sessionList = bean.data?.chatSessions else {
                return
            }
            guard let self else {
                return
            }
            let result : [String: ChatSession] =  data.reduce(into: [String: ChatSession]()) { partialResult, session in
                partialResult[session.id] = session
            }
            
            for var entry in sessionList {
                let item = result[entry.id]
                if(item != nil){
                    entry.setRowId(item!._id)
                }
            }
            
            // 进行本地的数据库的插入
            self.localModel.saveSession(sessionList)
            
            // UI diff 更新
            self.pullData.onNext(sessionList)
            
        } , onFailure: { error in
            print("allSession  2 " , error)
            
        }).disposed(by: rx.disposeBag)
    }
}

